package com.develop.system.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.develop.common.annotation.Log;
import com.develop.common.config.DevelopConfig;
import com.develop.common.controller.BaseController;
import com.develop.common.domain.FileDO;
import com.develop.common.domain.Tree;
import com.develop.common.service.FileService;
import com.develop.common.utils.MD5Utils;
import com.develop.common.utils.R;
import com.develop.common.utils.RandomValidateCodeUtil;
import com.develop.common.utils.ShiroUtils;
import com.develop.common.utils.StringUtils;
import com.develop.system.domain.MenuDO;
import com.develop.system.service.MenuService;
import com.develop.system.shiro.UnicomUsernamePasswordToken;
import com.develop.utils.AesEncryptUtils;

@Controller
public class LoginController extends BaseController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	MenuService menuService;
	@Autowired
	FileService fileService;
	@Autowired
	DevelopConfig developConfig;

	@GetMapping({ "/", "" })
	String welcome(Model model) {

		return "redirect:/login";
	}

	@Log("请求访问主页")
	@GetMapping({ "/index" })
	String index(Model model) {
		List<Tree<MenuDO>> menus = menuService.listMenuTree(getUserId());
		model.addAttribute("menus", menus);
		model.addAttribute("name", getUser().getName());
		FileDO fileDO = fileService.get(getUser().getPicId());
		if (fileDO != null && fileDO.getUrl() != null) {
			if (fileService.isExist(fileDO.getUrl())) {
				model.addAttribute("picUrl", fileDO.getUrl());
			} else {
				model.addAttribute("picUrl", "/img/photo_s.jpg");
			}
		} else {
			model.addAttribute("picUrl", "/img/photo_s.jpg");
		}
		model.addAttribute("username", getUser().getUsername());
		return "alarm/realtimealarm";
	}

	@GetMapping("/login")
	String login(Model model) {
		model.addAttribute("username", developConfig.getUsername());
		model.addAttribute("password", developConfig.getPassword());
		return "login";
	}

	@Log("登录")
	@PostMapping("/login")
	@ResponseBody
	R ajaxLogin(String username, String password, String verify, HttpServletRequest request) {
//		try {
//			// 从session中获取随机数
//			String random = (String) request.getSession().getAttribute(RandomValidateCodeUtil.RANDOMCODEKEY);
//			if (StringUtils.isBlank(verify)) {
//				return R.error("请输入验证码");
//			}
//			if (random.equals(verify)) {
//			} else {
//				return R.error("请输入正确的验证码");
//			}
//		} catch (Exception e) {
//			logger.error("验证码校验失败", e);
//			return R.error("验证码校验失败");
//		}
		try {
			username=AesEncryptUtils.decrypt(username, "581e75b6a87a6789");
			password=AesEncryptUtils.decrypt(password, "581e75b6a87a6789");
		} catch (Exception e1) {
			e1.printStackTrace();
			return R.error("登录出错");
		}
		password = MD5Utils.encrypt(username, password);
		UnicomUsernamePasswordToken token = new UnicomUsernamePasswordToken(username, password);
		token.setLoginType("sys");
		Subject subject = SecurityUtils.getSubject();
		try {
			subject.login(token);
			return R.ok();
		} catch (AuthenticationException e) {
			return R.error("用户或密码错误");
		}
	}

	@GetMapping("/logout")
	String logout() {
		ShiroUtils.logout();
		return "redirect:/login";
	}

	@GetMapping("/main")
	String main() {
		return "main";
	}

	/**
	 * 生成验证码
	 */
	@GetMapping(value = "/getVerify")
	public void getVerify(HttpServletRequest request, HttpServletResponse response) {
		try {
			response.setContentType("image/jpeg");// 设置相应类型,告诉浏览器输出的内容为图片
			response.setHeader("Pragma", "No-cache");// 设置响应头信息，告诉浏览器不要缓存此内容
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expire", 0);
			RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
			randomValidateCode.getRandcode(request, response);// 输出验证码图片方法
		} catch (Exception e) {
			logger.error("获取验证码失败>>>> ", e);
		}
	}

	@GetMapping(value = "/getVerifyCode")
	public void getVerifys(HttpServletRequest request, HttpServletResponse response) {
		try {
			response.setContentType("image/jpeg");// 设置相应类型,告诉浏览器输出的内容为图片
			response.setHeader("Pragma", "No-cache");// 设置响应头信息，告诉浏览器不要缓存此内容
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expire", 0);
			RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
			randomValidateCode.getRandcode(request, response);// 输出验证码图片方法
		} catch (Exception e) {
			logger.error("获取验证码失败>>>> ", e);
		}
	}
}
